<template>
  <el-dialog
    :title="`${drawerProps.title}突击申请`"
    v-model="drawerVisible"
    :draggable="true"
    :overflow="true"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    top="30px"
    width="600px"
    :destroy-on-close="true"
  >
    <el-alert
      type="info"
      description="1、法定假期突击不在系统内填写；
    2、非上级安排节假日突击请提前和上级沟通"
      show-icon
    >
    </el-alert>
    <br />
    <el-form
      ref="ruleFormRef"
      style="overflow-y: auto"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      label-width="120px"
      label-position="top"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item prop="workNote" label="突击工作内容">
        <el-input
          type="textarea"
          :rows="5"
          v-model="drawerProps.row.workNote"
          placeholder="1、突击工作涉及九天工单则填写单号和工作内容；
2、其他事项需写清楚突击工作内容，有工作产出佐证信息"
        ></el-input>
      </el-form-item>
      <el-form-item prop="isHoliday" label="">
        <el-switch v-model="holiday" disabled="true"> </el-switch>
        <span class="ml-2">是否节假日（系统根据配置判定）</span>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="drawerVisible = false">取消</el-button>
        <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">{{
          drawerProps.title.indexOf("新增") !== -1 ? "申请突击" : "确定"
        }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="UserDrawer">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { Params, RushJob, ManageUser } from "@/api/types/base";
import { BusinessType, BusinessOptType } from "@/enums/sysEnum";
import { useUserAction } from "@/hooks/useUserAction";
import apiService from "@/api/services/apiService";
import { useUserStore } from "@/stores/modules/user";

const { addUserAction } = useUserAction(BusinessType.RUSHJOB);
const userUser = useUserStore();

const rules = reactive({
  workNote: [{ required: true, message: "请输入突击内容" }]
});

const holiday = ref(false);
const isHoliday = async () => {
  let result: string = "0";
  let curDate = new Date();
  let curYear = curDate.getFullYear();
  let { data } = await apiService.findParam<Params>("HOLIDAY");
  if (data.exValue) {
    let exValue = JSON.parse(data.exValue);
    let yearHoliday = exValue["y" + curYear];
    if (yearHoliday) {
      let holiday = new Set(yearHoliday.holiday);
      let work = new Set(yearHoliday.work);
      let h = holiday.has(`${curDate.getFullYear()}-${curDate.getMonth() + 1}-${curDate.getDate()}`);
      let w = work.has(`${curDate.getFullYear()}-${curDate.getMonth() + 1}-${curDate.getDate()}`);
      if (h) {
        result = "1";
      } else if (w) {
        result = "0";
      } else {
        if (curDate.getDay() === 0 || curDate.getDay() === 6) {
          result = "1";
        }
      }
    }
  }
  holiday.value = result === "1";
  return result;
};

interface DrawerProps {
  title: string;
  tbName: string;
  isView: boolean;
  row: Partial<RushJob>;
  api?: (tabName: string, params: any) => Promise<any>;
  getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  tbName: "",
  row: {}
});

// 接收父组件传过来的环境
const acceptParams = async (params: DrawerProps) => {
  drawerProps.value = params;
  let flag = await isHoliday();
  let { data } = await apiService.find<ManageUser[]>("manage_user", { userId: userUser.userInfo._id });
  if (drawerProps.value.title.indexOf("新增") != -1) {
    drawerProps.value.row.isHoliday = flag;
    drawerProps.value.row.startTime = new Date();
    drawerProps.value.row.state = "0";
    drawerProps.value.row.userId = userUser.userInfo._id;
    drawerProps.value.row.email = userUser.userInfo.email;
    drawerProps.value.row.userName = userUser.userInfo.userName;
    drawerProps.value.row.workNo = userUser.userInfo.workNo;
    drawerProps.value.row.orgId = userUser.userInfo.orgId;

    if (data && data.length === 1) {
      drawerProps.value.row.charge_user = data[0].manage_user_rushjob;
    }
  } else if (drawerProps.value.row.isHoliday) {
    holiday.value = drawerProps.value.row.isHoliday === "1" ? true : false;
  }
  drawerVisible.value = true;
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      const data = await drawerProps.value.api!(drawerProps.value.tbName, drawerProps.value.row);
      ElMessage.success({ message: `${drawerProps.value.title}成功！` });
      if (drawerProps.value.title.indexOf("新增") != -1) {
        addUserAction(data._id, BusinessOptType.ADD, data.workNote);
      } else {
        addUserAction(drawerProps.value.row._id, BusinessOptType.UPDATE, drawerProps.value.row.workNote);
      }
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({
  acceptParams
});
</script>
